package com.macro.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.macro.mall.dao.CreditDao;
import com.macro.mall.entity.Credit;
import com.macro.mall.service.CreditService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Credit的服务接口的实现类
 *
 * @author
 */
@Service
public class CreditServiceImpl implements CreditService {
    private final Logger LOG = LogManager.getLogger(this.getClass());

    @Autowired
    private CreditDao creditDao;
    // TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化
    private static final int C200 = 200;
    private static final int C412 = 412;

    public String resultFormat(int code, Object data) {
        JSONObject result = new JSONObject();
        result.put("code", code);
        if (data != null) {
            result.put("data", data);
        }
        return result.toJSONString();
    }

    @Override
    public List<Credit> find(String name, Integer page, Integer size) {
        //TODO这里可以做通过Assist做添加查询
        PageHelper.startPage(page,size);
        List<Credit> result = creditDao.selectCreditByObj(Credit.builder().name(name).build());

        return result;
    }


    @Override
    public String saveNotNull(Credit value) {
        if (value == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("执行将Credit中属性值不为null的数据保存到数据库-->失败:对象不能为空");
            }
            return resultFormat(C412, null);
        }
        int result = creditDao.insertNotNullCredit(value);
        if (LOG.isDebugEnabled()) {
            LOG.debug("执行将Credit中属性值不为null的数据保存到数据库-->结果:", result);
        }
        return resultFormat(C200, result);
    }

    @Override
    public String updateNotNullById(Credit value) {
        if (value == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("执行通过Credit的id更新Credit中属性不为null的数据-->失败:对象为null");
            }
            return resultFormat(C412, null);
        }
        int result = creditDao.updateNotNullCreditById(value);
        if (LOG.isDebugEnabled()) {
            LOG.debug("执行通过Credit的id更新Credit中属性不为null的数据-->结果:", result);
        }
        return resultFormat(C200, result);
    }

    @Override
    public String deleteById(Integer id) {
        if (id == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("执行通过Credit的id删除Credit-->失败:id不能为空");
            }
            return resultFormat(C412, null);
        }
        int result = creditDao.deleteCreditById(id);
        if (LOG.isDebugEnabled()) {
            LOG.debug("执行通过Credit的id删除Credit-->结果:", result);
        }
        return resultFormat(C200, result);
    }


}